package test;

import atm.client.ATM;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

import static org.junit.Assert.assertEquals;

/**
 * Created by IntelliJ IDEA.
 * User: shesdmi
 * Date: 4/12/13
 * Time: 8:31 PM
 * To change this template use File | Settings | File Templates.
 */
public class ActorQueue implements Runnable{

    private CountDownLatch finishLatch;
    private CyclicBarrier startBarrier;
    private ATM atm;
    private final int queueId;
    private final int queueNum;
    private final int queueDepth;

    public ActorQueue(CountDownLatch finishLatch, CyclicBarrier startBarrier, ATM atm, int queueId, int queueNum, int queueDepth) {
        this.startBarrier = startBarrier;
        this.finishLatch = finishLatch;
        this.atm = atm;
        this.queueId = queueId;
        this.queueNum = queueNum;
        this.queueDepth = queueDepth;
    }

    public void run() {

        try {
            startBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            finishLatch.countDown();
            return;
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
            finishLatch.countDown();
            return;

        }

        for(int i = 0 ; i < queueDepth; i++) {

            StringBuilder id = new StringBuilder();
            id.append("test").append(queueId).append("-").append(i);

            StringBuilder account1 = new StringBuilder();
            if (queueId > 0)
                account1.append("test").append((queueId - 1)).append("-").append(i);
            else account1 = null;

            StringBuilder account2 = new StringBuilder();
            if (queueId < queueNum -1)
                account2.append("test").append((queueId + 1)).append("-").append(i);
            else account2 = null;

            atm.logon(id.toString(), id.toString().getBytes());
            atm.increase(10000);

            if( account1 != null ) {
                atm.transferTo(200, account1.toString());
            }

            if( account2 != null ) {
                atm.transferTo(200, account2.toString());
            }
            atm.logout();

        }


        finishLatch.countDown();
    }
}
